package com.yaorange.api;


import com.yaorange.common.constant.PerfectApiConstants;
import com.yaorange.common.core.domain.AjaxResult;
import com.yaorange.common.core.domain.entity.SysUser;
import com.yaorange.common.core.domain.model.LoginUser;
import com.yaorange.common.core.redis.RedisCache;
import com.yaorange.common.exception.ServiceException;
import com.yaorange.common.utils.DictUtils;
import com.yaorange.common.utils.SecurityUtils;
import com.yaorange.framework.web.service.TokenService;
import com.yaorange.nongjt.domain.NjtArea;
import com.yaorange.nongjt.domain.NjtLoginUser;
import com.yaorange.nongjt.domain.NjtUserPerfect;
import com.yaorange.nongjt.domain.NjtUserRegister;
import com.yaorange.nongjt.domain.response.ApiResponse;
import com.yaorange.nongjt.service.INjtAreaService;
import com.yaorange.nongjt.service.INjtUserPerfectService;
import com.yaorange.nongjt.service.INjtUserRegisterService;
import com.yaorange.system.mapper.SysUserMapper;
import com.yaorange.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;

@Slf4j
@Api(value = "会员管理", tags = "会员管理")
@RestController
@RequestMapping("/api")
public class NjtUserPerfectAPI {

    @Autowired
    INjtUserPerfectService njtUserPerfectService;

    @Autowired
    private INjtAreaService iNjtAreaService;


    /**
     * 获取省信息
     * @return
     */
    @ApiOperation("获取省信息")
    @GetMapping("/area/queryListRoot")
    public  AjaxResult queryPerfectUser() {
        List<NjtArea> areas = iNjtAreaService.getTreeNode();

        List<Map<String, String>> resultList = new ArrayList<>();

        for (NjtArea area : areas) {
            // 创建map并添加到结果列表中
            Map<String, String> itemMap = new HashMap<>();
            itemMap.put("name", area.getName());
            itemMap.put("code", area.getCode());

            resultList.add(itemMap);
        }
        return AjaxResult.success(resultList);
    }


    /**
     * 获取市信息
     * @return
     */

    @ApiOperation("获取市信息")
    @GetMapping("area/queryChildrenByParentCode")
    public  AjaxResult queryChirdrenByParentCode(@RequestParam String parentCode) {
        List<NjtArea> areas = iNjtAreaService.getByParentCode(parentCode);

        List<Map<String, String>> resultList = new ArrayList<>();

        for (NjtArea area : areas) {
            // 创建map并添加到结果列表中
            Map<String, String> itemMap = new HashMap<>();
            itemMap.put("name", area.getName());
            itemMap.put("code", area.getCode());
            resultList.add(itemMap);
        }

        return AjaxResult.success(resultList);
    }

    @ApiOperation("根据字典类型和字典标签获取字典值")
    @GetMapping("/common/queryDictLabelByValue")
    public AjaxResult getDictLabelByValue(
            @RequestParam String dictType,
            @RequestParam String dictValue) {
            // 获取字典标签
            String dictLabel = DictUtils.getDictLabel(dictType, dictValue);
            return AjaxResult.success(dictLabel);

    }



    @ApiOperation("根据字典类型获取字典所有标签")
    @GetMapping("/common/queryDictType")
    public AjaxResult getDict(@RequestParam String dictType) {
        String dictLabels = DictUtils.getDictLabels(dictType);
        String dictValues = DictUtils.getDictValues(dictType);

        List<String> labelsList = Arrays.asList(dictLabels.split(","));
        List<String> valuesList = Arrays.asList(dictValues.split(","));

        // 结果列表
        List<Map<String, String>> resultList = new ArrayList<>();

        for (int i = 0; i < labelsList.size(); i++) {
            // 提取label和value
            String[] labelParts = labelsList.get(i).split("\\.");
            String[] valueParts = valuesList.get(i).split("\\.");

            // 创建map并添加到结果列表中
            Map<String, String> itemMap = new HashMap<>();
            itemMap.put("dictLabel", labelParts[0]);
            itemMap.put("dictValue", valueParts[0]);

            resultList.add(itemMap);
        }
        return AjaxResult.success(resultList);
    }


    @ApiOperation("上传图片文件并返回文件地址")
    @PostMapping(value = "/common/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult uploadImageFile(
            @RequestPart("file") MultipartFile file, // 接收文件
            @RequestParam(value = "biz", required = false) String biz) { // 接收 biz 字段
        // 检查文件是否为空
        if (file.isEmpty()) {
            return AjaxResult.error("文件不能为空");
        }

        // 检查文件类型是否为图片
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return AjaxResult.error("仅支持上传图片文件（如 jpg, png, jpeg, gif）");
        }

        // 处理 biz 字段（如果存在）
        if (biz != null) {
            log.info("业务类型: {}", biz);
        }

        // 生成文件保存路径
        String uploadDir = "D:/实习工程实践/资料/基础代码/nongjt (2)/nongjt-serve/uploads/images"; // 修改为指定路径
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename(); // 生成唯一文件名
        String filePath = uploadDir + fileName;

        // 创建目录（如果不存在）
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 保存文件到本地
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            log.error("文件保存失败", e);
            return AjaxResult.error("文件保存失败");
        }

        // 返回文件访问地址
        String fileUrl ="http://localhost:8080/api/common/static/"+ fileName; // 与前端 viewUrl 兼容
        return AjaxResult.success(fileUrl);
    }







    @ApiOperation("提交更新的信息")
    @PostMapping("/user/perfect")
    public AjaxResult updatePerfect(@RequestBody NjtUserPerfect njtUserPerfect) {
        njtUserPerfectService.updateNjtUserPerfect(njtUserPerfect);
        return AjaxResult.success();
    }

}
